package com.yups.wxweb;

import com.yups.dao.CoachDao;
import com.yups.model.Coach;
import net.sf.json.JSONArray;
import org.gavaghan.geodesy.Ellipsoid;
import org.gavaghan.geodesy.GeodeticCalculator;
import org.gavaghan.geodesy.GeodeticCurve;
import org.gavaghan.geodesy.GlobalCoordinates;

import javax.servlet.annotation.WebServlet;
import java.util.List;
import java.util.Map;

/**
 * 获取距离数据
 *
 * @author 于鹏生
 */
@WebServlet(urlPatterns = "/wx/GetSkilledData")
public class GetSkilledData extends JsonServlet {
	private CoachDao coachDao=new CoachDao();
	@Override
	public String dealInput(Map<String, String[]> input) {
		double lat=0;
		double lon=0;
		try {
			lat = Double.parseDouble(input.get("lat")[0]);
			lon = Double.parseDouble(input.get("lon")[0]);
		} catch (NumberFormatException e) {
			e.printStackTrace();
		}
		List<Coach> coachs = coachDao.getAll();
		if(lat!=0) {
			for (Coach coach : coachs) {
				GlobalCoordinates source = new GlobalCoordinates(lat, lon);
			    GlobalCoordinates target =
						new GlobalCoordinates(coach.getLat(), coach.getLon());
			    double meter1 = getDistanceMeter(source, target, Ellipsoid.Sphere);
		        double meter2 = getDistanceMeter(source, target, Ellipsoid.WGS84);
				coach.setAvatar(IMG_PATH + coach.getAvatar());
				coach.setPhoto(IMG_PATH + coach.getPhoto());
		        coach.setDistance((long) meter2);
			}
		}
		return JSONArray.fromObject(coachs).toString();
	}
	
	public static double getDistanceMeter(GlobalCoordinates gpsFrom,
					 GlobalCoordinates gpsTo, Ellipsoid ellipsoid){
        GeodeticCurve geoCurve =
				new GeodeticCalculator().calculateGeodeticCurve(ellipsoid, gpsFrom, gpsTo);
        return geoCurve.getEllipsoidalDistance();
    }
}
